// pages/01homePage/04bill/bill.js
var app = getApp()
var appData = app.globalData
var sInfo = appData.shopInfo
var s = getApp().globalData.shopInfo
Page({
   data: {
      table: '',
      bill: '',
      totalPrice: '',
      zhekou: "",
      platform: '',
      tableInfo: '',
      print_prompt: '',
      devices: [],//蓝牙设备
      services: "", // 连接设备的服务
      bleConnect: true,
      writeServicweId: "", // 可写服务uuid  
      writeCharacteristicsId: "",//可写特征值uuid  
      // readServicweId: "", // 可读服务uuid  
      // readCharacteristicsId: "",//可读特征值uuid  
      // notifyServicweId: "", //通知服务UUid  
      // notifyCharacteristicsId: "", //通知特征值UUID
      printerList: [],
      showPrint: 0,
      bombBox: 0,
      numArray: [
         [9, 8.7, 8.4, 8.1],
         [7.8, 7.5, 7.3, 0]],
      call: 0
   },
   //弹框
   call: function () {
      this.setData({ call: !this.data.call })
   },
   //设置人数
   setGuestNum: function (e) {
      var num = e.currentTarget.id
      if (num > 0) {
         var total = this.data.bill.totalPrice
         var price = total * num * 0.1
         this.setData({
            totalPrice: price.toFixed(2),
            call: 0
         })
         console.log('this.data====', this.data)
      } else {
         this.reSetNum(num)
      }
   },
   //重设数字
   reSetNum: function (num) {
      var nA = this.data.numArray
      for (var i = 0; i < nA.length; i++) {
         var nA2 = nA[i]
         for (var j = 0; j < nA2.length; j++) {
            if (num == 0) {
               if (nA[i][j] == 15) nA[i][j] = -1
               else if (nA[i][j] > 15) nA[i][j] += 14
               else if (nA[i][j] > 0) nA[i][j] += 15
            } else {
               if (nA[i][j - 1] == 14) nA[i][j] = 15
               else if (nA[i][j] > 29) nA[i][j] -= 14
               else if (nA[i][j] > 0) nA[i][j] -= 15
            }
         }
      }
      this.setData({ numArray: nA })
   },

   maskHide: function () {
      this.setData({
         call: 0
      })
   },
   // 增加和减少
   add: function (e) {
      var b = this.data.bill
      var goodsInfo = b.list[e.currentTarget.id]
      var asa = goodsInfo.num++
      console.log('b==', b)
      // setDate页面数更新 data反
      this.setData({ bill: b })
      this.countNumAndPrice()
   },

   reduce: function (e) {
      var b = this.data.bill
      var i = e.currentTarget.id
      var goodsInfo = b.list[i]
      var n = --goodsInfo.num
      if (n == 0) {
         b.list.splice(i, 1)
      }
      console.log('b==', b)
      // setDate页面数更新 data反
      this.setData({ bill: b })
      this.countNumAndPrice()
   },

   countNumAndPrice: function () {
      var num = 0
      var price = 0
      var list = this.data.bill.list
      for (var i = 0; i < list.length; i++) {
         num += Number(list[i].num)
         price += (list[i].price * list[i].num)
      }
      this.setData({
         foodNum: num,
         totalPrice: price
      })
      console.log(num)
   },

   onLoad: function (opt) {
      var sys = wx.getSystemInfoSync()
      if (sys.platform == 'ios') {
         this.setData({ platform: 'ios' })
         this.openBluetooth()
      }

      var obj = JSON.parse(opt.table)
      wx.setNavigationBarTitle({
         title: obj.fenlei + obj.zhuo + '账单',
      })

      var param = {
         orderid: obj.orderid,
         seat_fee: appData.shopInfo.shopInfo.seat_fee
      }

      var that = this
      app.getJsonData('api/space/table_eat_bill.php', param, function (res) {
         if (res.code == 0) {
            that.setData({
               bill: res.data,
               table: obj
            })
            console.log('成功获取账单that.data', that.data)
         }
      })
   },

   checkout: function () {//结账ok
      var t = this
      var tab = t.data.table
      var tabName = tab.fenlei + tab.zhuo
      var param = {
         order_id: tab.orderid,
         seat_fee: appData.shopInfo.shopInfo.seat_fee,
         table: tabName,
         checkout_price: t.data.totalPrice ? t.data.totalPrice : t.data.bill.totalPrice,
         pay_waiter: appData.guestInfo.name,
         pay_waiter_id: appData.guestInfo.userid
      }
      console.log('checkout:', param)
      app.getNetData('order/mg/checkout', param, function (res) {
         console.log('结账结果')
         if (res.code == 0) {
            t.setData({ print_prompt: res.msg })
            t.listPrinter()
            t.readySendSocket(tabName, res.data)
         }
      })
   },

   listPrinter: function () {
      var t = this
      if (t.data.printerList.length == 0) {
         var param = { shop_id: appData.shopInfo.shopInfo.userid }
         app.getNetData('print2/mgr/getprinterlist', param, function (res) {
            t.setData({ printerList: res.data })
            t.checkPrint()
         })
      } else {
         t.checkPrint()
      }
   },

   checkPrint: function () {//检查是否可以直接打印
      if (this.data.printerList.length == 1) {
         var e = { currentTarget: { id: 0 } }
         this.clickSendPrint(e);
      } else {
         this.setData({ showPrint: 1 })
      }
   },
   //准备发送wss
   readySendSocket: function (table, rd) {
      appData.isWsSender = 1
      //msg数组结构：0桌号, 1状态, 2订单号, 3订单价格, 4点菜数量,5人数
      var m = {
         msg: rd,
         setMsg: table + '桌结账了'
      }
      var json = {
         type: 'say',
         to_client_id: 'all',
         content: JSON.stringify(m)
      }
      var msg = JSON.stringify(json)
      app.sendSocketMsg(msg)
   },

   wifiPrint: function (printer_id) {
      var that = this
      var obj = this.data.table
      var param = {
         printer_id: printer_id,
         orderid: obj.orderid,
         seat_fee: appData.shopInfo.seat_fee,
         shop_name: appData.shopInfo.shop,
         table_name: obj.fenlei + obj.zhuo
      }
      app.getJsonData('api/space/table_print.php', param, function (res) {
         wx.showToast({
            title: res.message,
            image: '/pages/images/qzg_logo_90x.jpg'
         })
         that.setData({
            showPrint: 0
         })
      })
   },

   sendPrint: function (e) {
      var index = e.currentTarget.id
      var p = this.data.printerList[index]
      if (p.type == 1) {
         this.wifiPrint(p.printer_id)
      } else if (p.type == 2) {
         this.readlyPrint(p.printer_id)
      } else {
         app.toast('暂只支持wifi和iphone蓝牙')
      }
   },

   bombBox: function (e) {
      this.setData({ btnArrIsShow: 1 })
   },

   confirm: function (e) {
      var total = this.data.bill.totalPrice
      var price = total * this.data.zhekou * 0.1
      this.setData({
         totalPrice: price.toFixed(2),
         btnArrIsShow: 0
      })
      console.log('this.data====', this.data)
   },

   inputZhekou: function (e) {
      var zk = e.detail.value
      this.setData({ zhekou: zk })
   },

   freeSingle: function () {
      var total = this.data.bill.totalPrice
      this.setData({
         totalPrice: 0,
         btnArrIsShow: 0
      })
   },

   priceEndClear: function () {
      var total = this.data.bill.totalPrice
      this.setData({
         totalPrice: parseInt(total),
         btnArrIsShow: 0
      })
   },
   //以下是全是蓝牙
   openBluetooth: function () {
      var that = this;
      if (wx.openBluetoothAdapter) {
         wx.openBluetoothAdapter({
            success: function (res) {
               console.log('1.初始化成功this.data：', that.data)
               that.searchBluetooth()
            },
            fail: function (res) {
               console.log('1.初始化失败this.data：', that.data)
               wx.showToast({
                  title: '蓝牙初始化失败',
               })
            },
         })
      } else {
         wx.showModal({
            title: '提示',
            content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
         })
      }
   },

   searchBluetooth: function () {
      var that = this;
      wx.startBluetoothDevicesDiscovery({
         services: [],
         success: function (res) {
            console.log('2.search成功了res', res)
            that.onBLEFound()
         },
         fail: function (res) {
            console.log('2.search失败了res', res)
            wx.showToast({
               title: 'searchBle失败',
            })
         },
      })
   },

   onBLEFound: function () {
      var bleId = wx.getStorageSync('ble_printer')
      var that = this
      wx.onBluetoothDeviceFound(function (res) {
         console.log('3.发现设备res', res)
         that.connectBLEDevice(bleId)
      })
   },

   connectBLEDevice: function (bleId) {
      var that = this;
      wx.createBLEConnection({
         deviceId: bleId,
         success: function (res) {
            console.log('4.连接蓝牙成功 :res', res, 'this.data', that.data)
            that.getBLEServices(bleId)
            that.stopSearchBLE()
            if (!that.data.bleConnect) {
               wx.showToast({
                  title: '蓝牙打印机连接失败，请检查【后台】->【设置】->【设置打印机】',
               })
               that.setData({ bleConnect: true })
            }
         },
         fail: function (res) {
            console.log('4.连接蓝牙失败 :res', res)
            wx.showToast({
               title: '蓝牙打印机连接失败，请检查【后台】->【设置】->【设置打印机】',
            })
            that.setData({ bleConnect: false })
         },
      })
   },

   stopSearchBLE: function () {
      wx.stopBluetoothDevicesDiscovery({
         success: function (res) {
            console.log('5.停止搜索了')
         },
         fail: function (res) { },
      })
   },

   /********************************************** */
   // 获取连接设备的service服务  
   getBLEServices: function (deviceId) {
      var that = this;
      wx.getBLEDeviceServices({
         // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取  
         deviceId: deviceId,
         success: function (res) {
            that.setData({
               services: res.services,
            })
            console.log('7.获取service服务成功res', res, 'this.data', that.data)
            that.getBLEChar(deviceId)
         },
         fail: function (res) {
            console.log('7.获取service服务失败res', res)
            wx.showToast({
               title: 'service服务获取失败',
            })
         },
      })
   },
   //获取连接设备的所有特征值  for循环获取不到值  
   getBLEChar: function (deviceId) {
      var that = this;
      wx.getBLEDeviceCharacteristics({
         deviceId: deviceId,
         serviceId: that.data.services[1].uuid,
         success: function (res) {
            for (var i = 0; i < res.characteristics.length; i++) {
               // if (res.characteristics[i].properties.notify) {
               //     that.setData({
               //         notifyServicweId: that.data.services[1].uuid,
               //         notifyCharacteristicsId: res.characteristics[i].uuid,
               //     })
               // }
               if (res.characteristics[i].properties.write) {
                  that.setData({
                     writeServicweId: that.data.services[1].uuid,
                     writeCharacteristicsId: res.characteristics[i].uuid,
                  })
               }
               // else if (res.characteristics[i].properties.read) {
               //     that.setData({
               //         readServicweId: that.data.services[1].uuid,
               //         readCharacteristicsId: res.characteristics[i].uuid,
               //     })
               // }
            }
            that.sendCommand('1b 40')
            console.log("8.2获取所有特征值成功：res", res, 'this.data', that.data);
         },
         fail: function (res) {
            console.log("8.2获取所有特征值失败：res", res);
         },
      })
   },

   readlyPrint: function (printer_id) {
      var t = this
      var param = {
         printer_id: printer_id,
         command: 'print',
         orderid: t.data.table.orderid
      }

      app.getJsonData('api/space/table_eat_print.php', param, function (res) {
         console.log('16进制res', res)
         if (res.code == 0) {
            t.printOut(res.data)
         }
      })
   },

   printOut: function (list) {
      for (var i = 0; i < list.length; i++) {
         this.sendCommand(list[i])
         this.sendCommand('1b 64 02')
      }
   },

   sendCommand: function (gbkStr) {
      var hex = gbkStr
      var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
         return parseInt(h, 16)
      }))
      var buffer1 = typedArray.buffer
      this.writeBLECharacteristicValue(hex, buffer1)
   },

   writeBLECharacteristicValue: function (hex, buffer) {
      var bleId = wx.getStorageSync('ble_printer')
      var that = this
      wx.writeBLECharacteristicValue({
         deviceId: bleId,
         serviceId: that.data.writeServicweId,
         characteristicId: that.data.writeCharacteristicsId,
         value: buffer,
         success: function (res) {
            var str = (hex == '1b 40' || hex == '1B 40') ? '蓝牙打印机初始化成功' : "蓝牙指令发送成功：" + JSON.stringify(res)
            console.log('打印状态', str)
         },
         fail: function (res) {
            wx.showToast({
               title: '蓝牙打印失败',
            })
         },
      })
   },
})
